import type { App, Directive } from 'vue'
import { usePermission } from '@/hooks/usePermission'

/**
 * v-permission 自定义指令
 * 用于控制具有权限的元素显示（无权限将从 DOM 移除）
 *
 * 用法：
 * <el-button v-permission="'SYS_USER_EDIT'">编辑</el-button>
 * <el-button v-permission="['PERM_1', 'PERM_2']">多权限</el-button>
 */
export const permissionDirective: Directive = {
  /**
   * @param binding 绑定值，例如：v-permission="'SYS_USER_EDIT'"
   */
  mounted(el, binding) {
    const { hasPermission } = usePermission()

    const value = binding.value
    if (!value) {
      console.warn('[v-permission] value is required!')
      return
    }

    // 如果用户没有权限，移除元素节点
    if (!hasPermission(value)) {
      el.parentNode?.removeChild(el)
    }
  }
}

export const setupPermissionDirective = (app: App) => {
  app.directive('permission', permissionDirective)
}
